package com.feilo.service;

import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.feilo.model.MileAge;
import com.feilo.util.BaseUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class DistanceService {
	
	/**
	 * 获取设备号在时间间隔内在历史轨迹点数据
	 * @param imei        设备号
	 * @param begin_time  开始时间
	 * @param end_time    结束时间
	 * @return            历史轨迹点数组
	 */
	public static String[] getWayPoint(String imei,long begin_time,long end_time){
		String sql = "select * from gpsdata where imei=? and gps_time between ? and ?";
		List<Record> data = Db.find(sql,new Object[]{imei,begin_time,end_time});
		int size = data.size();
		int step =  size%100 == 0 ? size/100 : size/100+1 ;
		String[] ret = new String[step];
		StringBuffer waypoints = null ;
	    for (int i = 0; i < step; i++) {
	    	waypoints = new StringBuffer();
	    	for(int j=0;j<100;j++){
	    		if(i*100+j==size) break ;
	    		waypoints.append(data.get(i*100+j).get("lng").toString()).append(",").append(data.get(i*100+j).get("lat").toString()).append(";");
	    	}
	    	waypoints.deleteCharAt(waypoints.length()-1);
	    	ret[i] = waypoints.toString();
	    	waypoints = null ;
	    }
		return ret ;
	}
	
	/**
	 * 根据历史轨迹点构造百度测距API的URL数组
	 * @param waypoints 历史轨迹点数组
	 * @return 百度测距API的URL数组
	 */
	public static String[] getDistanceURLs(String[] waypoints,String ak){
		String[] url = new String[waypoints.length];
		for(int i = 0 ; i<waypoints.length;i++){
			url[i] = "http://api.map.baidu.com/telematics/v3/distance?output=json&waypoints="+waypoints[i]+"&ak="+ak ;
		}
		return url ;
	}
	
	/**
	 * 根据百度测距API的URL计算相应的距离
	 * @param url 百度测距API的URL
	 * @return    实际距离
	 */
	public static float getDistanceData(String url){
		float distance = 0 ;
		//执行百度测距API的URL，并返回json格式的距离结果
		String distanceData = BaseUtil.getReturnData(url);
	    JSONObject distanceObject = new JSONObject(distanceData);
	    JSONArray results =distanceObject.getJSONArray("results");
	    for (int i = 0; i < results.length(); i++) {
	    	distance += results.getDouble(i);
	    }
	    return distance ;
	}
	
	/**
	 * 批量执行百度测距API的URL数组计算相应的距离，并返回对应的数组
	 * @param urls 百度测距API的URL数组
	 * @return     实际距离数组
	 */
	public static float[] getDistanceData(String[] urls){
		float[] ret = new float[urls.length];
		for(int i = 0;i<urls.length;i++){
		    ret[i]=getDistanceData(urls[i]);
		}
		return ret ;
	}
	
	/**
	 * 把设备号、日期、所经过距离等数据存入数据库
	 * @param imei     设备号
	 * @param date     日期
	 * @param distance 距离
	 */
	public static void insertDistance(String imei,Date date,float distance){
		String sql = "insert into mileage(imei,createtime,mileage) values(?,?,?)";
		Db.update(sql, new Object[]{imei, date, distance});
	}
	
	public static List<MileAge> getMileAgeList(String account){
		List<MileAge> list = MileAge.dao.find("select a.* from mileage a,devinfo b where a.imei=b.imei and b.account=?", new Object[]{account});
		return list ;
	}

}
